﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Asion.Dapper
{
    internal class TenantMananger
    {
        /// <summary>
        /// 库名对应处理
        /// </summary>
        private static ConcurrentDictionary<Type, string> tenants_manage = new ConcurrentDictionary<Type, string>();




        /// <summary>
        /// calss中主建属性缓存 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetTenantsName<TEntity>()
        {
            var type = typeof(TEntity);
            return GetTenantsName(type);
        }


        /// <summary>
        /// calss中主建属性缓存 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetTenantsName(Type type)
        {

            if (tenants_manage.TryGetValue(type, out string result))
            {
                return result;
            }
            var attributes = type.GetCustomAttributes(true).SingleOrDefault(attr => attr.GetType().Name == typeof(TenantAttribute).Name) as dynamic;
            if (attributes != null)
            {
                var name = attributes.Name;
                if (!DapperConfiguration.IsInitialize())
                {
                    DapperConfiguration.default_connection = name;
                }
                if (!tenants_manage.ContainsKey(type))
                {
                    tenants_manage.TryAdd(type, name); 
                }
                return name;
            }

            return DapperConfiguration.default_connection;
        }


        /// <summary>
        /// get master tenant name 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetMasterTenantsName()
        {
            return DapperConfiguration.default_connection;
        }
    }


}
